//
//  ITVolumeManager.m
//  InTubePro
//
//  Created by seven on 2020/2/5.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITVolumeManager.h"
#import <AVFoundation/AVFoundation.h>

#import <MediaPlayer/MediaPlayer.h>

@interface ITVolumeManager(){
    
    MPVolumeView *_volumeView;
    CGFloat _volume;
}
@end

@implementation ITVolumeManager

+ (instancetype)shareManager{
    static ITVolumeManager *_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = ITVolumeManager.new;
    });
    return _manager;
}


- (instancetype)init{
    self = [super init];
    if (self) {
        /*
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *error = nil;
        if (audioSession.otherAudioPlaying) {
            //有其他音乐在后台进行播放时，显示系统控件
            [audioSession setActive:NO error:&error];
        } else {
            //自己的应用会走这一步
            [audioSession setActive:YES error:&error];
        }
        //*/
        
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
        _volume = [AVAudioSession sharedInstance].outputVolume;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onVolumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
        [ITVolumeManager resumeBackgroundSound];
    }
    return self;
}


- (void)setVolume:(CGFloat)volume{
    _volume = volume;
    [self.systemSlider setValue:volume animated:YES];
}

- (UISlider *)systemSlider{
    if (_systemSlider) {
        return _systemSlider;
    }
    for (UISlider *view  in _volumeView.subviews) {
        if ([view isKindOfClass:UISlider.class]) {
            _systemSlider = view;
            break;
        }
    }
    return _systemSlider;
}

- (void)setIgnoreSystemVolume:(BOOL)ignoreSystemVolume{
    _ignoreSystemVolume = ignoreSystemVolume;
    if (_ignoreSystemVolume) {
        _volumeView = [[MPVolumeView alloc]initWithFrame:CGRectMake(1000, 0, 10, 10)];
        [UIApplication.sharedApplication.keyWindow addSubview:_volumeView];
    }else {
        [_volumeView removeFromSuperview];
        _volumeView = nil;
    }
}


- (void)onVolumeChanged:(NSNotification *)notification{
    
    float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
    if (fabs(_volume - volume) < 0.05) {
        return;
    }
    _volume = volume;
    NSLog(@"当前的音量 = %f", volume);
    
    if (self.customAction && _ignoreSystemVolume) {
        self.customAction(self, cat_update);
    }
}


/*
 * 继续播放后台背景音乐, 取消激活当前应用的audio session
 * @param error 设置失败时的错误信息
 **/
+ (void)resumeBackgroundSound {
    //Deactivate audio session in current app
    //Activate audio session in others' app depending on wether they listen to the Category changed
    //See here https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioGuidelinesByAppType/AudioGuidelinesByAppType.html#//apple_ref/doc/uid/TP40007875-CH11-SW1
    GlobalDelay(0, ^{
        NSError *error = nil;
       [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    });
    
}
 
/*
 * 暂停后台背景音乐的播放，激活当前应用的audio
 * @param error 设置失败时的错误信息
 **/
+ (void)pauseBackgroundSound{
    
    //See here https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/ConfiguringanAudioSession/ConfiguringanAudioSession.html#//apple_ref/doc/uid/TP40007875-CH2-SW1
    
    GlobalDelay(0, ^{
        NSError *error = nil;
        AVAudioSession *session = [AVAudioSession sharedInstance];
        //Set AVAudioSessionCategoryPlayback category mode for current app
        [session setCategory:AVAudioSessionCategoryPlayback error:&error];
        //Activate audio session in current app
        //Deactivate audio session in others' app
        if (session.otherAudioPlaying) {
            //有其他音乐在后台进行播放时，显示系统控件
            [session setActive:NO error:&error];
        } else {
            //自己的应用会走这一步
            [session setActive:YES error:&error];
        }
    });
    
    
}
 
+ (void)pauseBackgroundSoundWithCategoryRecord {
    GlobalDelay(0, ^{
        NSError *error = nil;
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryRecord error:nil];
        [session setActive:YES error:nil];
    });
}


@end
